package com.qf.java2106.huangshengrui.hotel.utils;

import com.alibaba.druid.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author q
 * @version 1.0
 * @date 2021-10-26
 **/
public class UploadFileUtils {

    public static String upload(HttpServletRequest request) {
        //上传文件
        try {
            Part part = request.getPart("imageUrl");
            String filename = part.getSubmittedFileName();
            if(StringUtils.isEmpty(filename)) {
                return "0";
            }
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String extName = filename.substring(filename.lastIndexOf("."));   //.jpg

            String destName = uuid + extName;  //上传的文件名称

            String path = request.getServletContext().getRealPath("/images/");

            File file = new File(path, destName);

            if(!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }

            part.write(file.getPath());
            //上传的图片应该保存下来     /images/huiguorou.jpg
            return "/images/" + destName;
        } catch (Exception e) {
            e.printStackTrace();
            return "-1";
        }


    }
}
